﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Helper
{
    public class SpinHelper : IDisposable
    {
        private bool isFinally;

        private SpinHelper()
        {
            isFinally = false;
        }

        public static IDisposable WaitResult(Action action, int millisecondsTimeout)
        {
            SpinHelper spinHelper = new SpinHelper();
            Task.Run(async () =>
            {
                while (!spinHelper.isFinally)
                {
                    await Task.Delay(millisecondsTimeout);
                    action();
                }
            });
            return spinHelper;
        }
        public static IDisposable WaitResult(Func<Task> action, int millisecondsTimeout)
        {
            SpinHelper spinHelper = new SpinHelper();
            Task.Run(async () =>
            {
                while (!spinHelper.isFinally)
                {
                    await Task.Delay(millisecondsTimeout);
                    await action();
                }
            });
            return spinHelper;
        }

        public void Dispose()
        {
            isFinally = true;
        }
    }
}
